#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cerrno>
#include <cstring>
#include <vector>
#include <functional>

using func_t = std::function<void(void)>;
std::vector<func_t> funcs;

void PrintLog()
{
    std::cout << "这是一个日志例程" << std::endl;
}
void OperMysql()
{
    std::cout << "这是一个操作数据库的例程" << std::endl;
}
void CheckNet()
{
    std::cout << "这是一个检测网络状态的例程" << std::endl;
}

void LoadTask()
{
    funcs.push_back(PrintLog);
    funcs.push_back(OperMysql);
    funcs.push_back(CheckNet);
}

void SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL); // 获取状态描述符
    if (fl < 0)
    {
        std::cerr << "error string " << strerror(errno) << std::endl;
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK); // 修改状态为非阻塞
}

void HanderAllTask()
{
    for (auto func : funcs)
        func();
}

int main()
{
    char buffer[64];
    SetNonBlock(0);
    LoadTask();
    while (true)
    {
        std::cout << "Enter# " << std::endl;
        ssize_t n = read(0, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n - 1] = '\0';
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "end file" << std::endl;
            break;
        }
        else
        {
            if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "data is not ready" << std::endl;
                HanderAllTask();
                sleep(1);
                continue;
            }
            else if (errno == EINTR)
                continue;

            else
            {
                std::cerr << "read error " << strerror(errno) << std::endl;
            }
        }
    }
    return 0;
}